﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace DotNet.Common
{
    public class StringHelper
    {


        #region 转换人民币大小金额
        /// <summary> 
        /// 转换人民币大小金额 
        /// </summary> 
        /// <param name="num">金额</param> 
        /// <returns>返回大写形式</returns> 
        public static string DecimalToRMB(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }

        #endregion

        #region 转换人民币大小金额  (一个重载，将字符串先转换成数字在调用CmycurD)
        /// <summary> 
        /// 转换人民币大小金额  (一个重载，将字符串先转换成数字在调用CmycurD)
        /// </summary> 
        /// <param name="num">用户输入的金额，字符串形式未转成decimal</param> 
        /// <returns></returns> 
        public static string StringToRMB(string numstr)
        {
            try
            {
                decimal num = Convert.ToDecimal(numstr);
                return DecimalToRMB(num);
            }
            catch
            {
                return "非数字形式！";
            }
        }
        #endregion

        #region 将全角数字转换为数字
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }
        #endregion

        #region Json 操作
        /// <summary>
        /// Json特符字符过滤，参见http://www.json.org/
        /// </summary>
        /// <param name="sourceStr">要过滤的源字符串</param>
        /// <returns>返回过滤的字符串</returns>
        public static string JsonCharFilter(string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\\b");
            sourceStr = sourceStr.Replace("\t", "\\\t");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\f", "\\\f");
            sourceStr = sourceStr.Replace("\r", "\\\r");
            return sourceStr.Replace("\"", "\\\"");
        }

        /// <summary>
        /// 将数据表转换成JSON类型串
        /// </summary>
        /// <param name="dt">要转换的数据表</param>
        /// <returns></returns>
        public static StringBuilder DataTableToJSON(System.Data.DataTable dt)
        {
            return DataTableToJson(dt, true);
        }

        /// <summary>
        /// 将数据表转换成JSON类型串
        /// </summary>
        /// <param name="dt">要转换的数据表</param>
        /// <param name="dispose">数据表转换结束后是否dispose掉</param>
        /// <returns></returns>
        public static StringBuilder DataTableToJson(System.Data.DataTable dt, bool dt_dispose)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("[\r\n");

            //数据表字段名和类型数组
            string[] dt_field = new string[dt.Columns.Count];
            int i = 0;
            string formatStr = "{{";
            string fieldtype = "";
            foreach (System.Data.DataColumn dc in dt.Columns)
            {
                dt_field[i] = dc.Caption.ToLower().Trim();
                formatStr += "'" + dc.Caption.ToLower().Trim() + "':";
                fieldtype = dc.DataType.ToString().Trim().ToLower();
                if (fieldtype.IndexOf("int") > 0 || fieldtype.IndexOf("deci") > 0 ||
                    fieldtype.IndexOf("floa") > 0 || fieldtype.IndexOf("doub") > 0 ||
                    fieldtype.IndexOf("bool") > 0)
                {
                    formatStr += "{" + i + "}";
                }
                else
                {
                    formatStr += "'{" + i + "}'";
                }
                formatStr += ",";
                i++;
            }

            if (formatStr.EndsWith(","))
            {
                formatStr = formatStr.Substring(0, formatStr.Length - 1);//去掉尾部","号
            }
            formatStr += "}},";

            i = 0;
            object[] objectArray = new object[dt_field.Length];
            foreach (System.Data.DataRow dr in dt.Rows)
            {

                foreach (string fieldname in dt_field)
                {
                    objectArray[i] = dr[dt_field[i]].ToString().Trim();
                    switch (objectArray[i].ToString())
                    {
                        case "True":
                            {
                                objectArray[i] = "true"; break;
                            }
                        case "False":
                            {
                                objectArray[i] = "false"; break;
                            }
                        default: break;
                    }
                    i++;
                }
                i = 0;
                stringBuilder.Append(string.Format(formatStr, objectArray));
            }
            if (stringBuilder.ToString().EndsWith(","))
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);//去掉尾部","号
            }

            if (dt_dispose)
            {
                dt.Dispose();
            }
            return stringBuilder.Append("\r\n];");
        }
        #endregion

        #region 生成指定数量的html空格符号
        /// <summary>
        /// 生成指定数量的html空格符号
        /// </summary>
        public static string GetSpacesString(int spacesCount)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < spacesCount; i++)
            {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }
        #endregion

        #region 删除字符串尾部的回车/换行/空格
        /// <summary>
        /// 删除字符串尾部的回车/换行/空格
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RTrim(string str)
        {
            for (int i = str.Length; i >= 0; i--)
            {
                if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
                {
                    str.Remove(i, 1);
                }
            }
            return str;
        }
        #endregion

        #region 处理危险字符串

        /// <summary>
        /// 危险字符
        /// </summary>
        /// <param name="strarr">要判断字符串数组</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string[] strarr)
        {
            bool isTrue = false;

            for (int i = 0; i < strarr.Length; i++)
            {
                if (Regex.IsMatch(strarr[i], @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%||\*|!|\']"))
                {
                    isTrue = true;
                    break;
                }
            }

            return isTrue;
        }

        /// <summary>
        /// 检测是否有危险的可能用于链接的字符串
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeUserInfoString(string str)
        {
            return Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest");
        }


        /// <summary>
        /// 清理html 字符串
        /// </summary>
        /// <param name="strIn"></param>
        /// <returns></returns>
        public static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"<html>|</html>|<span>|</span>|<br>|<br/>|<br />|&nbsp;|<meta http-equiv=Content-Type content=|<head>|</head>|<meta name=Generator content=|<style>|</style>|<body lang=ZH-CN style='text-justify-trim:punctuation'>|</body>|</div>|</p>|<span lang=EN-US>|<p class=MsoNormal>|text/html; charset=gb2312|Microsoft Word 11 (filtered)|<!-- /* Font Definitions */ @font-face|/* Style Definitions */|/* Page Definitions */|</td>|</tr>|</table>", "");
        }

        ///// <summary>
        ///// 清理字符串
        ///// </summary>
        //public static string CleanInput(string strIn)
        //{
        //    return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        //}
        
        #region 过滤 Sql 语句字符串中的注入脚本
       
        /// <summary>
        /// 过滤 Sql 语句字符串中的注入脚本
        /// </summary>
        /// <param name="source">传入的字符串</param>
        /// <returns></returns>      
        public static string FilterSql(string source)
        {
            //单引号替换成两个单引号
            if (source == null)
            {
                return "";
            }
            source = source.Replace("'", "''");
            //半角封号替换为全角封号，防止多语句执行
            source = source.Replace(";", "；");
            source = source.Replace("--", "－－");
            //半角括号替换为全角括号
            source = source.Replace("(", "（");
            source = source.Replace(")", "）");
            ///////////////要用正则表达式替换，防止字母大小写得情况////////////////////
            //去除执行存储过程的命令关键字
            source = source.Replace("Exec", "");
            source = source.Replace("Execute", "");
            //去除系统存储过程或扩展存储过程关键字
            source = source.Replace("xp_", "x p_");
            source = source.Replace("sp_", "s p_");
            //防止16进制注入
            source = source.Replace("0x", "0 x");
            return source;
        }

        #endregion

        #endregion

        #region 对表 表单内容进行转换HTML操作
        /**/
        /// <summary>
        /// 功能:对表 表单内容进行转换HTML操作,
        /// </summary>
         /// <param name="fString">html字符串</param>
         /// <returns></returns>
         public static string HtmlCode(string fString)
         {
             string str = "";
             str = fString.Replace(">", "&gt;");
             str = fString.Replace("<", "&lt;");
             str = fString.Replace(" ", "&nbsp;");
             str = fString.Replace("\n", "<br />");
             str = fString.Replace("\r", "<br />");
             str = fString.Replace("\r\n", "<br />");
 
             return str;
         }
         
        #endregion         
        
        #region 截取字符串
        /// <summary>
        /// 字符截取
        /// </summary>
        /// <param name="sInString">text:文本</param>
        /// <param name="iCutLength">length 长度(汉字、中文符号算字节,英文符号算一个字节）</param>
         /// <returns>字符截取截取后的字符串</returns> 
        public static string CutString(string sInString, int iCutLength,bool addPoint)
         {
             if (sInString == null || sInString.Length == 0 || iCutLength <= 0)
                 return "";
             int iCount = System.Text.Encoding.GetEncoding("Shift_JIS").GetByteCount(sInString);
             if (iCount > iCutLength)
             {
                 int iLength = 0;
                 for (int i = 0; i < sInString.Length; i++)
                 {
                     int iCharLength = System.Text.Encoding.GetEncoding("Shift_JIS").GetByteCount(new char[] { sInString[i] });
                     iLength += iCharLength;
                     if (iLength == iCutLength)
                     {
                         sInString = sInString.Substring(0, i + 1);
                         break;
                     }
                     else if (iLength > iCutLength)
                     {
                         sInString = sInString.Substring(0, i);
                         break;
                     }
                 }

                 if(addPoint){sInString+="...";}
             }
             return sInString;
         } 
        #endregion

        #region 字符串分函数
        //// <summary>
       /// 字符串分函数
       /// </summary>
       /// <param name="strID"></param>
       /// <param name="index"></param>
       /// <param name="Separ"></param>
       /// <returns></returns>
       public string StringSplit(string strings, int index, string Separ)
       {
           string[] s = strings.Split(char.Parse(Separ));
           return s[index];
       }
      #endregion 
        
        #region 分解字符串为数组
       /**/
        /// <summary>
        /// 字符串分函数
        /// </summary>
        /// <param name="str">要分解的字符串</param>
        /// <param name="splitstr">分割符,可以为string类型</param>
        /// <returns>字符数组</returns>
        public static string[] splitstr(string str, string splitstr)
        {
            if (splitstr != "")
            {
                System.Collections.ArrayList c = new System.Collections.ArrayList();
                while (true)
                {
                    int thissplitindex = str.IndexOf(splitstr);
                    if (thissplitindex >= 0)
                    {
                        c.Add(str.Substring(0, thissplitindex));
                        str = str.Substring(thissplitindex + splitstr.Length);
                    }
                    else
                    {
                        c.Add(str);
                        break;
                    }
                }
                string[] d = new string[c.Count];
                for (int i = 0; i < c.Count; i++)
                {
                    d[i] = c[i].ToString();
                }
                return d;
            }
            else
            {
                return new string[] { str };
            }
        }
        #endregion  
		
        #region 检测一个字符符,是否在另一个字符中,存在,存在返回true,否则返回false
        //// <summary>
        /// 检测一个字符符,是否在另一个字符中,存在,存在返回true,否则返回false
        /// </summary>
        /// <param name="srcString">原始字符串</param>
        /// <param name="aimString">目标字符串</param>
        /// <returns></returns>
        public static bool IsEnglish(string srcString, string aimString)
        {
            bool Rev = true;
            string chr;
            if (aimString == "" || aimString == null) return false;
            for (int i = 0; i < aimString.Length; i++)
            {
               chr = aimString.Substring(i, 1);
                if (srcString.IndexOf(chr) < 0)
                {
                    return false;
                    //break;
                }

            }
            return Rev;
        }
        #endregion         
        
        #region 检测字符串中是否含有中文及中文长度
        //// <summary>
        /// 检测字符串中是否含有中文及中文长度
        /// </summary>
        /// <param name="str">要检测的字符串</param>
        /// <returns>中文字符串长度</returns>
        public static int CnStringLength(string str)
        {
            ASCIIEncoding n = new ASCIIEncoding();
            byte[] b = n.GetBytes(str);
            int l = 0;  // l 为字符串之实际长度 
            for (int i = 0; i <= b.Length - 1; i++)
            {
                if (b[i] == 63)  //判断是否为汉字或全脚符号 
                {
                    l++;
                }
            }
            return l;
        
        }
        #endregion 
        
        #region 取字符串右侧的几个字符
        //// <summary>
        /// 取字符串右侧的几个字符
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="length">右侧的几个字符</param>
        /// <returns></returns>
        public static  string GetStrRight(string str, int length)
        {
            string Rev = "";

            if (str.Length < length)
            {
                Rev = str;

            }
            else
            {
                Rev = str.Substring(str.Length - length, length);
            }
            return Rev;


        }
        #endregion 
        
        #region 替换右侧的字符串

        //// <summary>
        /// 替换右侧的字符串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="strsrc">右侧的字符串</param>
        /// <param name="straim">要替换为的字符串</param>
        /// <returns></returns>
        public static  string RepStrRight(string str, string strsrc, string straim)
        {

            string Rev = "";
            if (GetStrRight(str, strsrc.Length) != strsrc)
            {
                Rev = str;
            }
            else
            {
                Rev = str.Substring(0, str.Length - strsrc.Length).ToString() + straim.ToString();
            }
            return Rev;
        }
        #endregion

	   public static string[] GetStrArray(string str)
        {
            return str.Split(new char[',']);
        }

        public static string GetArrayStr(List<string> list,string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }

        #region 删除最后一个字符之后的字符

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str,string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        #endregion

        ///   内容摘要：按字节截断字符串。   
        ///   </summary>   
        public static string GetSubString(string mText, int startIndex, int byteCount)
        {
            if (byteCount < 1) return string.Empty;

            if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount)
            {
                return mText;
            }
            else
            {
                if (startIndex == 0)
                {
                    byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText);
                    byte[] newBytes = new byte[byteCount];

                    for (int i = 0; i < byteCount; i++)
                        newBytes[i] = txtBytes[i];

                    return System.Text.Encoding.Default.GetString(newBytes);
                }
                else
                {
                    string tmp = GetSubString(mText, 0, startIndex - 1);
                    mText = mText.Substring(tmp.Length);
                    return GetSubString(mText, 0, byteCount);
                }
            }
        }


        public static string GetSubString(string mText, int startIndex, int byteCount,bool addStr)
        {
            if (byteCount < 1) return string.Empty;

            if (System.Text.Encoding.Default.GetByteCount(mText) <= byteCount)
            {
                if (addStr)
                {
                    mText += "...";
                }
                return mText;
            }
            else
            {
                if (startIndex == 0)
                {
                    byte[] txtBytes = System.Text.Encoding.Default.GetBytes(mText);
                    byte[] newBytes = new byte[byteCount];

                    for (int i = 0; i < byteCount; i++)
                        newBytes[i] = txtBytes[i];

                    string strret = System.Text.Encoding.Default.GetString(newBytes);

                    if (addStr)
                    {
                        strret += "...";
                    }
                    return strret;
                }
                else
                {
                    string tmp = GetSubString(mText, 0, startIndex - 1);
                    mText = mText.Substring(tmp.Length);
                    return GetSubString(mText, 0, byteCount);
                }
            }
        }


        public static string GetSubString(string mText, int startIndex)
        {
            return GetSubString(mText, startIndex, System.Text.Encoding.Default.GetByteCount(mText) - startIndex + 1);
        }



    }
}
